package xyz.mumu233.muxinnetty.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import xyz.mumu233.muxinnetty.mapper.UsersMapper;
import xyz.mumu233.muxinnetty.pojo.Users;
import xyz.mumu233.muxinnetty.service.UserService;
import xyz.mumu233.muxinnetty.utils.FastDFSClient;
import xyz.mumu233.muxinnetty.utils.FileUtils;
import xyz.mumu233.muxinnetty.utils.QRCodeUtils;

import java.io.IOException;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private Sid sid;

    @Autowired
    private QRCodeUtils qrCodeUtils;

    @Autowired
    private FastDFSClient fastDFSClient;

    @Override
    public boolean queryUsernameIsExist(String username) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        Users result = usersMapper.selectOne(queryWrapper);
        return result != null ? true : false;
    }

    @Override
    @Transactional
    public Users queryUserForLogin(String username, String pwd) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",pwd);
        Users result = usersMapper.selectOne(queryWrapper);
        return result;
    }

    @Override
    public Users save(Users users) {

        String userId = sid.nextShort();

        String qrCodePath = "D://user" + userId + "qrcode.png";
        //muxin_qrcode:[username]
        qrCodeUtils.createQRCode(qrCodePath,"muxin_qrcode:" + users.getUsername());
        MultipartFile qrCodeFile = FileUtils.fileToMultipart(qrCodePath);
        String qrCodeUrl="";
        try {
            qrCodeUrl = fastDFSClient.uploadQRCode(qrCodeFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        users.setQrcode(qrCodeUrl);
        users.setId(userId);

        usersMapper.insert(users);
        return users;
    }

    @Override
    public Users updateUserInfo(Users u) {
        Users users = usersMapper.selectById(u.getId());
        users.setFaceImage(u.getFaceImage());
        users.setFaceImageBig(u.getFaceImageBig());

        usersMapper.updateById(users);
        return  usersMapper.selectById(u.getId());
    }

    @Override
    public Users updateUserNickNmae(Users users) {
        Users u = usersMapper.selectById(users.getId());
        u.setNickname(users.getNickname());

        usersMapper.updateById(u);
        return usersMapper.selectById(users.getId());
    }
}
